<template>
  <Container>
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="search"></SearchForm>
    </template>
    <template v-slot:content>
      <div class="tableContent">
        <div class="status">
          <div class="statusItem">所选日期：{{ chooseTime || '暂未选择时间' }}</div>
          <div class="statusItem">所选区域：{{ chooseArea.areaName || '暂未选择区域' }}</div>
          <div class="statusItem">能源类型：{{ chooseEnergy.energyName || '暂未选择源类型' }}</div>
          <div class="statusItem">累计能耗量：{{ consumptionValue }}{{ chooseEnergy.energyUnit || '' }}</div>
          <ReportButton :reportData="reportData" :apiAddress="apiAddress" filename="能源报表"></ReportButton>
        </div>
        <div class="table">
          <TableData :tableThead="tableThead" :dataList="dataList" :loading="loading" :page="page" :size="size"
            :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
            <template v-slot:consumption="{ row }">
              {{ row.consumption }}{{ row.energyUnit }}
            </template>
          </TableData>
        </div>
      </div>
    </template>
  </Container>
</template>

<script>
import dataQueryApi from "@/api/dataQuery"
import areaApi from "@/api/area"
import energyApi from "@/api/energy"
import { getRecentTimeRange, formatDate, displayDate } from "@/utils/filterTime"


import ReportButton from "@/components/ReportButton"
import Container from "@/components/Container"
export default {
  name: 'DailyReport',
  components: { Container, ReportButton },
  data() {
    return {
      dialogVisible: false,
      addEditFlag: '',
      btnList: ['add', 'delete'],
      size: 10,
      page: 1,
      total: 10,
      dataList: [],
      areaList: [],
      energyList: [],
      chooseArea: {},
      chooseEnergy: {},
      chooseTime: '',
      formItemList: [
        {
          label: '选择区域',
          type: 'select',
          selectOptions: [],
          param: 'areaId',
          defaultSelect: '',
          multiple: false,
        },
        {
          label: '选择能源类型',
          type: 'select',
          selectOptions: [],
          param: 'energyId',
          defaultSelect: '',
          multiple: false,
        },
        {
          label: '选择日期',
          type: 'daterange',
          param: 'dateTime',
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          defaultSelect: getRecentTimeRange('week'),
        },
      ],
      tableThead: [
        { label: '日期/时间', prop: 'recordTime' },
        { label: '能源类型', prop: 'energyName' },
        { label: '能源数据', slotName: 'consumption' },
      ],
      consumptionValue: 0,
      searchFormData: {},
      reportData: {},
      apiAddress: dataQueryApi.exportDayReport,
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    async initData() {
      let { data: areaList } = await areaApi.queryByCondition({});
      let { data: energyList } = await energyApi.queryByCondition({})
      this.areaList = areaList || [];
      this.energyList = energyList || [];
      this.searchFormData = {
        areaId: this.areaList[0]?.areaId || '',
        energyId: this.energyList[0]?.energyId || '',
        dateTime: getRecentTimeRange('week', true),
        startTime: getRecentTimeRange('week', true)[0],
        endTime: getRecentTimeRange('week', true)[1]
      }
      this.setFormOptions();
      this.queryPageByCondition();
    },
    queryConsumption() {
      let { areaId, energyId, startTime, endTime } = this.searchFormData;
      if (energyId && startTime && endTime) {
        dataQueryApi.queryConsumption({
          areaId,
          energyId,
          startTime: startTime ? startTime + ' 00:00:00' : '',
          endTime: endTime ? endTime + ' 23:59:59' : '',
        }).then(res => {
          this.consumptionValue = res.data || 0
        })
      } else {
        this.consumptionValue = 0
      }
    },
    getLabel(list, key, id) {
      return list.find(e => e[key] == id) || {}
    },
    getChooseItem() {
      let { areaId, energyId, startTime, endTime } = this.searchFormData;
      let areaList = JSON.parse(JSON.stringify(this.areaList))
      let energyList = JSON.parse(JSON.stringify(this.energyList))
      this.chooseArea = areaList.find(e => e.areaId == areaId) || {};
      this.chooseEnergy = energyList.find(e => e.energyId == energyId) || {};
      this.chooseTime = startTime && endTime ? `${formatDate(new Date(startTime), true)}至${displayDate(formatDate(new Date(endTime), true))}` : ""
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('areaId') !== -1) {
          let selectOptions = this.areaList.map(data => {
            return {
              text: data.areaName, value: data.areaId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('energyId') !== -1) {
          let selectOptions = this.energyList.map(data => {
            return {
              text: data.energyName, value: data.energyId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
      })
    },
    //查询表单数据
    queryPageByCondition() {
      console.log(this.searchFormData)
      let { startTime, endTime, areaId, energyId } = this.searchFormData
      if (!energyId) {
        this.page = 1;
        this.size = 10;
        this.total = 10;
        this.dataList = [];
        this.consumptionValue = '--';
        this.chooseEnergy.energyUnit = '';
        this.chooseEnergy.energyName = '';
        return
      }
      let organizationNo = sessionStorage.organizationNo
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          startTime: startTime ? startTime + ' 00:00:00' : '',
          endTime: endTime ? endTime + ' 23:59:59' : '',
          areaId,
          energyId,
          organizationNo
        }
      }
      this.getChooseItem()
      this.queryConsumption();
      dataQueryApi.longReport(params).then(res => {
        if (res.code == 1) {
          let { content, totalElements } = res.data || {}
          this.dataList = content || [];
          this.dataList.forEach(e => {
            e.energyUnit = this.getLabel(this.energyList, 'energyId', e.energyId).energyUnit
            e.recordTime = formatDate(new Date(e.recordTime), true)
          })
          this.total = totalElements || 10;
        } else {
          this.dataList = [];
        }
        this.loading = false;
      }).catch(err => {
        this.loading = false;
      })
    },
    getReportData() {
      let { startTime, endTime, areaId, energyId } = this.searchFormData
      this.reportData = {
        startTime: startTime ? startTime + ' 00:00:00' : '',
        endTime: endTime ? endTime + ' 23:59:59' : '',
        areaId,
        energyId
      }
    },
    search(data) {
      this.page = 1;
      this.searchFormData = {
        ...this.searchFormData,
        ...data,
        startTime: data.dateTime ? data.dateTime[0] : '',
        endTime: data.dateTime ? data.dateTime[1] : ''
      };
      this.getReportData();
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
}
</script>

<style lang="scss" scoped>
.tableContent {
  width: 100%;
  height: 100%;
  padding: 20px;
  background-color: #ffffff;

  .status {
    width: 100%;
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .statusItem {
      height: 52px;
      background: linear-gradient(323deg, rgba(97, 118, 208, 0.24) 0%, rgba(147, 201, 255, 0.24) 100%);
      line-height: 52px;
      padding: 0 20px;
      margin-right: 12px;
      border-radius: 5px;
      font-size: 20px;
      color: #333333;
    }
  }

  .table {
    width: 100%;
    height: calc(100% - 70px);
  }
}
</style>